from waitress import serve

from configs.global_config import global_config
from flask_server import (
    LISTEN_HOST,
    PORT,
    app,
    deregister_from_nacos,
    register_to_nacos,
)
from utils.logger_config import get_logger_config

if __name__ == "__main__":
    try:
        # 初始化全局配置
        print("正在初始化全局配置...")
        global_config.initialize()
        print("全局配置初始化完成")
        
        # 配置日志
        print("正在配置日志...")
        logger = get_logger_config(name="run_with_waitress").get_logger()
        logger.info("日志配置完成")
        
        # 注册到Nacos
        print("正在注册到Nacos...")
        register_to_nacos()
        logger.info("Nacos注册完成")
        
        # 检查Flask应用是否正确初始化
        print(f"Flask应用: {app}")
        print(f"监听地址: {LISTEN_HOST}")
        print(f"端口: {PORT}")
        
        # 使用waitress启动服务(配置4个工作线程)
        workers = global_config.get("waitress.workers", 4)
        logger.info(f"正在使用Waitress启动服务，地址: {LISTEN_HOST}，端口: {PORT}，线程数: {workers}")
        print(f"正在使用Waitress启动服务，地址: {LISTEN_HOST}，端口: {PORT}，线程数: {workers}")
        
        serve(app, host=LISTEN_HOST, port=PORT, threads=workers)
        
    except KeyboardInterrupt:
        print("接收到终止信号，正在关闭服务...")
        if 'logger' in locals():
            logger.info("接收到终止信号，正在关闭服务...")
    except Exception as e:
        print(f"启动过程中发生错误: {str(e)}")
        import traceback
        print("详细错误信息:")
        traceback.print_exc()
        if 'logger' in locals():
            logger.error(f"启动过程中发生错误: {str(e)}")
            logger.error(f"详细错误信息: {traceback.format_exc()}")
    finally:
        try:
            print("正在从Nacos注销...")
            # 从Nacos注销
            deregister_from_nacos()
            if 'logger' in locals():
                logger.info("从Nacos注销完成")
            print("从Nacos注销完成")
        except Exception as e:
            print(f"注销过程中发生错误: {str(e)}")
            if 'logger' in locals():
                logger.error(f"注销过程中发生错误: {str(e)}")
